package com.bootlever.framework.core.configuration;

import com.bootlever.framework.common.utils.StringUtils;
import com.bootlever.framework.core.properties.BasicProperties;
import com.bootlever.framework.core.properties.basic.Cors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@ConditionalOnExpression("'${bootlever.framework.basic.cors.enable:false}'=='true'")
public class CorsConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private BasicProperties basicProperties;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        if (basicProperties == null || basicProperties.getCors() == null) {
            return;
        }
        Cors cors = basicProperties.getCors();
        if (StringUtils.isBlank(cors.getAddMapping())) {
            return;
        }
        if (cors.isEnbale() == false) {
            return;
        }
        CorsRegistration corsRegistration = null;
        corsRegistration = registry.addMapping(cors.getAddMapping());
        if (StringUtils.isNotBlank(cors.getAllowedOrigins())) {
            corsRegistration.allowedOrigins(cors.getAllowedOrigins().split(","));
        }
        if (StringUtils.isNotBlank(cors.getAllowedMethods())){
            corsRegistration.allowedMethods(cors.getAllowedMethods().split(","));
        }
        if (StringUtils.isNotBlank(cors.getAllowedHeaders())){
            corsRegistration.allowedHeaders(cors.getAllowedHeaders().split(","));
        }
        if (StringUtils.isNotBlank(cors.getExposeHeaders())){
            corsRegistration.exposedHeaders(cors.getExposeHeaders().split(","));
        }
        corsRegistration.allowCredentials(cors.isAllowedCredentials());
        corsRegistration.maxAge(cors.getMaxAge());

    }
}
